package com.chen.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.chen.pojo.Role;
import com.chen.pojo.User;
import com.chen.service.role.RoleService;
import com.chen.service.user.UserService;
import com.chen.tools.Constants;
import com.chen.tools.PageSupport;
import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping("/user")
public class UserController {
	private Logger logger = Logger.getLogger(UserController.class);
	@Resource(name="userService")
	private UserService userService;
	@Resource(name="roleService")
	private RoleService roleService;

	@RequestMapping(value = "/login")
	public String login() {
		logger.debug("UserController welcome SMBMS==============================");
		return "jsp/login";
	}

	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
	public String doLogin(String userCode, String userPassword, HttpSession session) {
		logger.debug("doLogin=====================================");
		// ����service�����������û�ƥ��
		User user = new User();
		try {
			user = userService.login(userCode, userPassword);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (null != user) {// ��¼�ɹ�
			// ҳ����ת(frame.jsp)
			session.setAttribute(Constants.USER_SESSION, user);
			session.setAttribute("userId", user.getId());
			session.setAttribute("userCode", user.getUserCode());
			session.setAttribute("userPassword", user.getUserPassword());
			return "redirect:/user/main";
			// response.senRedirect("jsp/frame.jsp");
		} else {
			// ҳ����ת(login.jsp)
			// session.setAttribute("error", "�û��������벻��ȷ!");
			return "redirect:/user/exlogin";
		}
	}

	@RequestMapping(value = "main")
	public String main(HttpSession session) {
		if (session.getAttribute(Constants.USER_SESSION) == null) {
			return "redirect:/user/login";
		}
		return "jsp/frame";
	}

	@RequestMapping(value = "exlogin", method = RequestMethod.GET)
	public String exLogin(String userCode, String userPassword, HttpSession session) {
		logger.info("exLogin =====================");
		userCode = (String) session.getAttribute("userCode");
		userPassword = (String) session.getAttribute("userPassword");
		User user = new User();
		try {
			user = userService.login(userCode, userPassword);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (!user.getUserCode().equals(userCode)) {
			throw new RuntimeException("�û���������!");
		}
		if (!user.getUserPassword().equals(userPassword)) {
			throw new RuntimeException("�����������!");
		}
		return "redirect:/user/main";
	}
	// �ֲ��쳣����
	/*
	 * @ExceptionHandler(value={RuntimeException.class}) public String
	 * handlerException(RuntimeException e, HttpServletRequest req){
	 * req.setAttribute("e", e); return "error"; }
	 */

	@RequestMapping(value = "/userlist")
	public String getUserList(Model model, @RequestParam(value = "queryname", required = false) String queryUserName,
			@RequestParam(value = "queryUserRole", required = false) String queryUserRole,
			@RequestParam(value = "pageIndex", required = false) String pageIndex) {
		logger.info("getUserList --- > queryUserName:" + queryUserName);
		logger.info("getUserList --- > queryUserRole:" + queryUserRole);
		logger.info("getUserList --- > pageIndex:" + pageIndex);
		int _queryUserRole = 0;
		List<User> userList = null;
		// ����ҳ������
		int pageSize = Constants.pageSize;
		// ��ǰҳ��
		int currentPageNo = 1;
		if (queryUserName == null) {
			queryUserName = "";
		}
		if (queryUserRole != null && !queryUserRole.equals("")) {
			_queryUserRole = Integer.parseInt(queryUserRole);
		}
		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (NumberFormatException e) {
				return "redirect:/user/syserror";
			}
		}
		// ������(��)
		int totalCount = 0;
		try {
			totalCount = userService.getUserCount(queryUserName, _queryUserRole);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// ��ҳ��
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);
		int totalPageCount = pages.getTotalPageCount();
		// ������ҳ��βҳ
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		try {
			userList = userService.getUserList(queryUserName, _queryUserRole, currentPageNo, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("userList", userList);
		List<Role> roleList = new ArrayList<Role>();
		try {
			roleList = roleService.getRoleList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("roleList", roleList);
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		return "jsp/userlist";
	}

	@RequestMapping(value = "/syserror")
	public String sysError() {
		return "jsp/syserror";
	}

	@RequestMapping(value = "/useradd", method = RequestMethod.GET)
	public String addUser(@ModelAttribute("user") User user, Model model) {
		model.addAttribute("user", user);
		return "jsp/useradd";
	}

	/**
	 * ���ļ��ϴ�
	 * 
	 * @param user
	 * @param session
	 * @param request
	 * @param attach
	 * @return
	 */
	/*
	 * @RequestMapping(value="/addsave.html",method=RequestMethod.POST) public
	 * String addUserSave(User user,HttpSession session, HttpServletRequest
	 * request,
	 * 
	 * @RequestParam(value="a_idPicPath",required=false) MultipartFile attach){
	 * String idPicPath = null; //�ж��ļ��Ƿ�Ϊ�� if(!attach.isEmpty()){ String path =
	 * request.getSession().getServletContext()
	 * .getRealPath("statics"+File.separator+"uploadfiles");
	 * logger.info("uploadFile===================== >" + path); String
	 * oldFileName = attach.getOriginalFilename();//Դ�ļ���
	 * logger.info("uploadFile oldFileName===================== >" +
	 * oldFileName); String prefix =
	 * FilenameUtils.getExtension(oldFileName);//Դ�ļ���׺
	 * logger.info("uploadFile prefix===================== >" + prefix); int
	 * filesize = 500000;
	 * logger.info("uploadFile filesize===================== >" + filesize);
	 * if(attach.getSize() > filesize){//�ϴ���С���ó���500KB
	 * request.setAttribute("uploadFileError", " * �ϴ���С���ó���500KB"); return
	 * "useradd"; } else if (prefix.equalsIgnoreCase("jpg") ||
	 * prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") ||
	 * prefix.equalsIgnoreCase("pneg")){//�ϴ�ͼƬ��ʽ����ȷ String fileName =
	 * System.currentTimeMillis() +
	 * RandomUtils.nextInt(1000000)+"_Personal.jpg";
	 * logger.info("uploadFile fileName===================== >" + fileName);
	 * File targetFile = new File(path, fileName); if(!targetFile.exists()){
	 * targetFile.mkdirs(); } //���� try { attach.transferTo(targetFile); } catch
	 * (Exception e) { e.printStackTrace();
	 * request.setAttribute("uploadFileError", "�ϴ�ʧ��!"); return "useradd"; }
	 * idPicPath = path+File.separator+fileName; } else {
	 * request.setAttribute("uploadFileError", " * �ϴ���С���ó���500KB"); return
	 * "useradd"; } }
	 * user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).
	 * getId()); user.setCreationDate(new Date()); user.setIdPicPath(idPicPath);
	 * if(userService.add(user)){ return "redirect:/user/userlist.html"; }
	 * return "useradd"; }
	 */
	/**
	 * ���ļ��ϴ�
	 * 
	 * @param user
	 * @param session
	 * @param request
	 * @param attachs
	 * @return
	 */
	@RequestMapping(value = "/addsave", method = RequestMethod.POST)
	public String addUserSave(User user, HttpSession session, HttpServletRequest request,
			@RequestParam(value = "attachs", required = false) MultipartFile[] attachs) {
		String idPicPath = null;
		String workPicPath = null;
		String errorInfo = null;
		boolean flag = true;
		String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
		for (int i = 0; i < attachs.length; i++) {
			MultipartFile attach = attachs[i];
			if (i == 0) {
				errorInfo = "uploadFileError";
			} else if (i == 1) {
				errorInfo = "uploadWpError";
			}
			String oldFileName = attach.getOriginalFilename();// Դ�ļ���
			String prefix = FilenameUtils.getExtension(oldFileName);// Դ�ļ���׺
			int filesize = 500000;
			if (attach.getSize() > filesize) {
				request.setAttribute(errorInfo, " * �ϴ���С���ó���500KB");
				flag = false;
			} else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {// �ϴ�ͼƬ��ʽ����ȷ
				String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
				File targetFile = new File(path, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				// ����
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute(errorInfo, "�ϴ�ʧ��!");
					flag = false;
				}
				if (i == 0) {
					idPicPath = path + File.separator + fileName;
				} else if (i == 1) {
					workPicPath = path + File.separator + fileName;
				}
			} else {
				request.setAttribute(errorInfo, " * �ϴ�ͼƬ��ʽ����ȷ!");
			}
		}
		if (flag) {
			user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
			user.setCreationDate(new Date());
			user.setIdPicPath(idPicPath);
			user.setWorkPicPath(workPicPath);
			try {
				if (userService.add(user)) {
					return "redirect:/user/userlist";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "jsp/useradd";
	}

	@RequestMapping(value = "/usermodify", method = RequestMethod.GET)
	public String getUserById(@RequestParam String uid, Model model) {
		logger.debug("getUserById uid=====================" + uid);
		User user = new User();
		try {
			user = userService.getUserById(uid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("user", user);
		return "jsp/usermodify";
	}

	@RequestMapping(value = "/usermodifysave", method = RequestMethod.POST)
	public String modifyUserSave(User user, HttpSession session) {
		logger.debug("modifyUserSave userid====================" + user.getId());
		user.setModifyBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
		user.setModifyDate(new Date());
		try {
			if (userService.modify(user)) {
				return "redirect:/user/userlist";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "jsp/usermodify";
	}

	@RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
	public String view(@PathVariable String id, Model model) {
		logger.debug("view id=====================" + id);
		User user = new User();
		try {
			user = userService.getUserById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("user", user);
		return "jsp/userview";
	}

	@RequestMapping(value = "/ucexist")
	@ResponseBody
	public Object userCodeIsExit(@RequestParam String userCode) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		if (StringUtils.isNullOrEmpty(userCode)) {
			resultMap.put("userCode", "exist");
		} else {
			User user = new User();
			try {
				user = userService.selectUserCodeExist(userCode);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (null != user) {
				resultMap.put("userCode", "exist");
			} else {
				resultMap.put("userCode", "noexist");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}

	@RequestMapping(value = "/views", method = RequestMethod.GET)
	@ResponseBody
	public User views(@RequestParam String id) {
		User user = new User();
		try {
			user = userService.getUserById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	@RequestMapping(value = "/pwd", method = RequestMethod.GET)
	public String pwdgo() {
		return "jsp/pwdmodify";
	}

	@RequestMapping(value = "/passwordmodify", method = RequestMethod.POST)
	public String pwdModify(@RequestParam String oldpassword, @RequestParam String newpassword) {
		User user = new User();
		try {
			user = userService.getUserPwd(oldpassword);
		} catch (Exception e) {
			e.printStackTrace();
		}
		boolean flag = false;
		if (user != null) {
			try {
				flag = userService.updatePwd(user.getId(), newpassword);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (flag) {
				logger.debug("�޸ĳɹ���");
				return "redirect:/user/userlist";
			} else {
				logger.debug("�޸�ʧ�ܣ�");
				return "redirect:/user/pwd";
			}
		}
		return null;
	}

	@RequestMapping(value = "/upass")
	@ResponseBody
	public Object viewpwd(HttpSession session, String oldpassword) {
		Map<String, Object> map = new HashMap<String, Object>();
		String userCode = (String) session.getAttribute("userCode");
		if (StringUtils.isNullOrEmpty(oldpassword)) {
			map.put("oldpassword", "exist");
		} else {
			User user = new User();
			try {
				user = userService.selectUserCodeExist(userCode);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (null != user) {
				User user1 = new User();
				try {
					user1 = userService.getUserPwd(oldpassword);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (user1 != null) {
					if (user.getUserPassword().equals(user1.getUserPassword())) {
						map.put("oldpassword", "exist");
					} else {
						map.put("oldpassword", "noexist");
					}
				} else {
					map.put("oldpassword", "noexist");
				}
			}
		}
		return JSONArray.toJSONString(map);
	}

	@RequestMapping(value="/rolelist",method=RequestMethod.GET,produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public List<Role> getRoleList(){
		List<Role> list = null;
		try {
			list = roleService.getRoleList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	@RequestMapping(value="/delete",method=RequestMethod.GET)
	@ResponseBody
	public Object deleteUser(@RequestParam String uid){
		boolean flag = false;
		try {
			flag = userService.deleteUserById(Integer.parseInt(uid));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if(flag){
			map.put("delResult", "true");
		} else {
			map.put("delResult", "false");
		}
		return JSONArray.toJSONString(map);
	}
}
